package com.koron.css2.serviceManage.impl;

import com.koron.common.mapper.PrintMapper;
import com.koron.css2.ServerInterface;
import com.koron.css2.serviceManage.bean.RequestBean;
import com.koron.css2.serviceManage.bean.UserInfoBean;
import com.koron.util.Constant;
import com.koron.util.DBSourceUtils;
import org.apache.commons.lang3.StringUtils;
import org.koron.ebs.mybatis.SessionFactory;
import org.swan.bean.MessageBean;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

/**
 * 打印样式选择界面，用户可以选择采用哪一个模板来打印
 * @author admin
 *
 */
public class PrintTemplateUserList implements ServerInterface {

	@Override
	public MessageBean<?> exec(SessionFactory factory, UserInfoBean userInfo, RequestBean req) {

		@SuppressWarnings("rawtypes")
		MessageBean<ArrayList> info = MessageBean.create(Constant.MESSAGE_INT_SUCCESS, "success", ArrayList.class);

		try {
			//查询出测试用打印样式数据
			String companyNo = ((Map)req.getData()).get("companyNo")+"";
			String code = ((Map)req.getData()).get("code")+"";
			PrintMapper mapper = factory.getMapper(PrintMapper.class,"_default");
			String bid = mapper.getBusinuessIdByCode(code);
			mapper = factory.getMapper(PrintMapper.class,DBSourceUtils.getDbEnv(companyNo));
			ArrayList<HashMap<String,String>> list = mapper.getTemplateDefault(bid);
			ArrayList<HashMap<String,String>> newlist = new ArrayList<>();
			for (HashMap<String,String> m : list) {
				String scope = m.get("SCOPE");
				if(StringUtils.isBlank(scope)) {
					HashMap<String,String> n = new HashMap<>();
					n.put("id", m.get("ID"));
					n.put("name", m.get("NAME"));
					newlist.add(n);
				}else {
					String us[] = scope.split("[,，;；]{1}");
					boolean found = false;
					for (String u :us) {
						if(userInfo.getUserInfo().getAcount().equals(u)) {
							found = true;
							break;
						}
					}
					if(found) {
						HashMap<String,String> n = new HashMap<>();
						n.put("id", m.get("ID"));
						n.put("name", m.get("NAME"));
						newlist.add(n);
					}
				}
			}
			info.setData(newlist);
		} catch (Exception e) {
			info.setCode(Constant.MESSAGE_INT_FAIL);
			info.setDescription(e.getMessage());
			logger.error(e.getMessage(), e);
		}
		return info;
	}

}
